package com.itheima.task;

import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class ImgDeleteTask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil util;

    /**
     * 实现图片删除，被执行的任务功能
     * @throws Exception
     */
    @Scheduled(cron = "* 1 * * * ?")
    public void imgDelete() throws Exception{
        log.info("自动清除垃圾图片");
        SetOperations set = redisTemplate.opsForSet();

        //利用交集和补集计算出差集并存入补集
        Set union = set.union("origin_", "upload_");
        Set intersect = set.intersect("origin_", "upload_");
//        Set union = set.union("origin_", "upload_");
        for (Object o : intersect) {
            union.remove(o);
        }

        if(union != null && union.size() != 0) {
            for (Object s : union) {

                //阿里云删除文件
                util.delete(String.valueOf(s));
            }
            Set upload = set.members("upload_");

            for (Object o : upload) {
                set.remove("upload_", o);
            }

            Set origin = set.members("origin_");
            for (Object o : origin) {
                set.add("upload_",o);
            }

        }
    }
}
